package com.huichenghe.xinlvsh01.Ble;

import java.io.UnsupportedEncodingException;

/**
 * 打开电话和短信提醒的管理类
 * Created by lixiaoning on 15-12-2.
 */
public class BleForPhoneAndSmsRemind extends BleBaseDataManage
{
    public static final byte toDevice = (byte)0x05;
    public static final byte formDevice = (byte)0x85;

    public static final byte startPhoneRemindToDevice = (byte)0x01;
    public static final byte startSmsRemindToDevice = (byte)0x0B;

    /**
     * 手机请求打开手环来电提醒功能
     */
    public void openThePhoneAndSmsRemind(byte ba)
    {
        byte[] data = new byte[3];
        data[0] = (byte)0x00;
        data[1] = (byte)ba;
        data[2] = (byte)0x01;

        setMsgToByteDataAndSendToDevice(toDevice, data, data.length, true);

    }


    /**
     * 发送提醒数据给手环
     * @param phoneNumber
     * @param contactName
     */
    public void startPhoneAndSmsRemind(String phoneNumber, String contactName, byte ba)
    {
        if(phoneNumber.startsWith("+86"))
        {   // 去掉 +86
            phoneNumber = phoneNumber.substring(3);
        }
        // 字符串转化为字符数组
        char[] chars = phoneNumber.toCharArray();
        byte[] pnum = new byte[chars.length];
        for (int i = 0; i < chars.length; i++)
        {
            pnum[i] = (byte)(chars[i] & 0xff);
        }


        if(contactName != null && !contactName.equals(""))
        {   // 如果有联系人名字
            if(contactName.getBytes().length < 32)
            {
                byte[] bytes = null;
                try {
                    bytes = contactName.getBytes("UTF-8");  // 以utf-8编码转化为byte数组
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                byte[] allData = new byte[16 + bytes.length];
                for (int i = 0; i < 16 && i < 11; i ++)
                {
                    allData[i + 1] = pnum[i];
                }
                for (int i = 16; i < allData.length; i ++)
                {
                    allData[i] = bytes[i - 16];
                }


                pnum = allData;
            }
            else
            {
                return;
            }


        }
        else
        {
            // 只有电话号码
            byte[] phoneData = new byte[16];
            for (int i = 0; i < phoneData.length && i < pnum.length; i ++)
            {
                phoneData[i + 1] = pnum[i];
            }
                pnum = phoneData;
        }


        setMsgToByteDataAndSendToDevice(ba, pnum, pnum.length, true);

    }


}
